<?php
namespace App\Libraries;

use Illuminate\Support\Facades\DB;

trait Tools
{

    public $config=[];

    public function __construct(){
        $QiniuConfig = DB::table('config_qiniu')->limit(1)->first();
        if($QiniuConfig){
            $QiniuConfig_json = json_encode($QiniuConfig);
            $QiniuConfig = json_decode($QiniuConfig_json,true);
        }else{
            $QiniuConfig = [];
        }
        $this->config = $QiniuConfig;
    }

	//生成Token
	public static function MakeToken(int $uid){
		$token = md5(microtime(true).$uid);
		return $token;
	}

    /**
     * 无限极数结构
     */
    public static function tree(array $array, int $pid = 0, string $pname = 'pid', string $cname = 'child')
    {
        $tree = array();
        foreach ($array as $k => $v) {
            if ($v[$pname] == $pid) {
                unset($array[$k]);
                $v[$cname] = self::tree($array, $v['id']);
                if (!$v[$cname])
                    unset($v[$cname]);
                $tree[] = $v;
            }
        }
        return $tree;
    }

	//Token加密
	public function TokenEncrypt(int $uid, $token){
		#UF997097637021
		$key = 'UF((&)(&^#&)@!';
		$encryptToken = base64_encode(openssl_encrypt("{$uid}:{$token}", 'DES-EDE3', $key, OPENSSL_RAW_DATA));
		return $encryptToken;
	}



    public  function createBetweenMonth()
    {
        $tomonth   = mktime(0, 0, 0, date('m'), 1, date('Y'));
        $betWeen[] = [
            $tomonth,
            $tomonth + 2592000
        ];
        for ($i = 0; $i < 15; $i++) {
            $betWeen[] = [
                mktime(0, 0, 0, date('m') - ($i + 1), 1, date('Y')),
                mktime(0, 0, 0, date('m') - $i, 1, date('Y'))
            ];
        }
        return array_reverse($betWeen);
    }

    public  function creatDateMonth(array $between)
    {
        $date = [];
        foreach ($between as $k => $v) {
            $date[] = date('Y-m', $v[0]);
        }
        return $date;
    }

    public  function createBetween(int $start, int $time = 86400)
    {
        $betWeen[] = [
            $start,
            $start + $time
        ];
        for ($i = 0; $i < 15; $i++) {
            $betWeen[] = [
                $start - $time * ($i + 1),
                $start - $time * $i
            ];
        }
        return array_reverse($betWeen);
    }

    public  function creatDate(string $form = "m-d", array $between, int $time = 86400)
    {
        foreach ($between as $k => $v) {
            $date [] = date($form, $v[1] - $time);
        }
        return $date;
    }


}

